<?php
namespace sql;
class DataBaseAttribute{
    //字段：name,sql\SqlField.php
    private $fields = array();

    function __construct()
    {
    }

    function getPrimaryKey()
    {
        foreach($this->fields as $n => $field)
        {
            if($field->primary)
                return $field;
        }
        return null;
    }

    function bindColumns($fs/**array */){
        $this->fields = $fs;
    }

    function getColumns(){
        return $this->fields;
    }

    /**
     * 获取所有字段名称
     * id,name,age,sex
     */
    function getColumnNames()
    {
        $names = array();
        foreach($this->fields as $n => $v)
        {
            //$v=>SqlField
            $names[] = $v->name;
        }
        return join(",",$names);
    }

    /**
     * 获取所有字段变量名称
     * :id,:name,:age,:sex
     */
    function getColumnPars()
    {
        $names = array();
        foreach($this->fields as $n => $v)
        {
            //$v=>SqlField
            $names[] = ":".$v->name;
        }
        return join(",",$names);
    }

    /**
     * 获取所有字段变量名称
     * id=:id,name=:name,age=:age,sex=:sex
     * $cols 指定列名
     */
    function getColumnSets($cols="",$withPK=false)
    {
        $keys = explode(",",$cols);
        $names = array();
        foreach($this->fields as $n => $v)
        {
            //忽略主键
            if($v->primary) continue;

            //未指定列，返回所有列
            if(empty($cols))
            {
                //$v=>SqlField
                $names[] = $v->name."=:".$v->name;
            }//指定了列
            else
            {
                if(in_array($v->name,$keys))
                    $names[] = $v->name."=:".$v->name;
            }
        }
        return join(",",$names);
    }

    /**
     * 将类成员变量的值绑定到PDOStatement
     */
    function bindStmt(&$stmt/** PDOStatement */)
    {
        $ref = new \ReflectionClass($this);

        foreach($this->fields as $n => $field)
        {
            $pro = $ref->getProperty($n);
            $val = $pro->getValue($this);
            $stmt->bindValue($field->pdoParam(),$val,$field->pdoType());
        }
    }
}
?>